/**
 * 核心技术支持
 * IT渠道网 小程序商城
 * 13873174181 微信同号
 */
import {My} from '../my/my-model.js';
import {Product} from '../product/product-model.js';
import {Cart} from '../cart/cart-model.js';
var my = new My();
var product = new Product();
var cart = new Cart();

Page({
    data: {
      isRuleTrue: false,
      showHot: false,
      addressInfo: null,
      mydata: {'balance':0, 'couponNum':0}
    },
    onLoad: function() {
      this.loadHotList();
    },
    /**
     * 加载数据
     */
    onShow: function() {
      this._findMyData();
      this._loadHead();
      // cartNum
      var num = cart.getCartTotalCounts().counts2;
      if (num > 0) {
        wx.setTabBarBadge({
          index: 2,
          text: num.toString()
        })
      } else {
        wx.removeTabBarBadge({
          index: 2
        })
      }
    },
    /**
     * 用户信息
     */
    _loadHead: function() {
      var that = this;
      // 查看是否授权
      wx.getSetting({
        success: function(res){
          if (res.authSetting['scope.userInfo']) {
            my.getUserInfo((data)=>{
              that.setData({
                userInfo: data
              })
            })
          } else {
            that.setData({
              isRuleTrue: true
            })
          }
        }
      })
    },
    /**
     * bind
     */
    onGotUserInfo: function (e) {
      var that = this;
      that.setData({
        isRuleTrue: false
      })
      if (e.detail.errMsg == 'getUserInfo:ok') {
        my.getUserInfo((data)=>{
          that.setData({
            userInfo: data
          })
        }, 1)
      } else {
        that.setData({
          isRuleTrue: true
        })
      }
    },
    /**
     * 订单统计
     */
    _findMyData: function() {
      var that = this;
      my.findMyData((data)=>{
        data.balance = Number(data.balance).toFixed(2);
        that.setData({
          mydata: data
        })
      })
    },
    /**
     * 相关推荐
     */
    loadHotList: function() {
      var that = this;
      product.getHotData(2, (data) => {
        // 截取字符
        for (var i in data) {
          data[i].goodsName = data[i].goodsName.substring(0, 32);
          data[i].price = data[i].price.toFixed(2);
        }
        that.setData({
          hotData: data,
          showHot: true
        })
      })
    },
    /**
     * 商品详情
     */
    onProductsItemTap: function(event) {
      var id = product.getDataSet(event, 'id');
      wx.navigateTo({
        url: '../product/product?id=' + id
      })
    }
})